# coding=utf-8
import json

from api.notification.model import LastMsg, ShortMsg, MsgDetail
from common.cache import redis_cache
from common.notification import db as db
from common.notification.model import USER_NOTIFY_TYPES
from common.utils import exceptions as err
from common.utils.api import page2offset
from common.utils.tz import utc_to_local_str
from common.notification import templates
from common.notification import db as notification_db
from common.notification.model import NOTIFY_TYPE
from common.cache import redis_cache


def create_last_msg_lite(msg, default_title=None):
    """
    消息分类列表要显示最近一条消息的title和created_at
    """
    last_msg = LastMsg()
    content = json.loads(msg.content) if msg else {}
    last_msg.title = content.get('title') or default_title
    last_msg.tag = content.get('tag')
    last_msg.body = content.get('body') or content.get('content') or u"暂无最新消息"
    last_msg.created_at = utc_to_local_str(msg.created_at) if msg else ''
    return last_msg


def get_unread_count(user_id):
    count = 0
    for notify_type in USER_NOTIFY_TYPES:
        count += redis_cache.get_unread_notify_count(user_id, notify_type)
    return count


def view_notifications(user_id, notify_type, page, size):
    limit, offset = page2offset(page, size, max_size=30, default_size=20)
    notify_list = db.get_notifications(user_id, notify_type, limit, offset)
    _list = []
    for notify in notify_list:
        short_msg = ShortMsg()
        short_msg.id = notify.id
        short_msg.created_at = utc_to_local_str(notify.created_at)
        short_msg.read = notify.read
        content = json.loads(notify.content)
        short_msg.content = {
            'tag': content['tag'],
            'title': content['title'],
            'body': content.get('body') or content.get('content')
        }
        if (notify_type == 1) and notify.extend:
            # 中獎更新資料
            short_msg.content.update(json.loads(notify.extend) or {})
        short_msg.command = notify.command
        _list.append(short_msg)
    return _list


def view_single_notification(user_id, notify_id):
    notify = db.get_notify_by_id(notify_id)
    if not notify:
        raise err.ResourceNotFound('')
    if notify.notify_type in USER_NOTIFY_TYPES and notify.user_id != user_id:
        raise err.PermissionError('not access')
    detail = MsgDetail()
    detail.id = notify.id
    detail.created_at = utc_to_local_str(notify.created_at)
    detail.read = notify.read
    content = json.loads(notify.content)
    detail.content = {
        'tag': content.get('tag', ''),
        'title': content.get('title', ''),
    }
    if content.get('body', None):
        detail.content['body'] = content.get('body', '')
    else:
        detail.content['body'] = content.get('content', '')
    return detail
